package com.yxy.service;

import com.github.pagehelper.PageHelper;
import com.yxy.base.BusinessException;
import com.yxy.dao.SysLoginInfoMapper;
import com.yxy.dao.PersonMapper;
import com.yxy.dto.SysLoginInfoDto;
import com.yxy.feign.VO.AdminUserInToken;
import com.yxy.model.SysLoginInfo;
import com.yxy.utils.TenantHelper;
import com.yxy.utils.TokenCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

@Slf4j
@Service
public class SysLoginInfoService {


  @Resource
  private HttpServletRequest request;

  @Autowired
  private TokenCheckUtil tokenCheckUtil;

  @Resource
  private PersonMapper personMapper;

  @Resource
  private SysLoginInfoMapper SysLoginInfoMapper;

  @Autowired
  private TenantHelper tenantHelper;


  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public SysLoginInfo save() throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    SysLoginInfo entity = new SysLoginInfo();
    entity.setUserName(adminUser.getAdminUser().getUsername());
    try{
    InetAddress addr = InetAddress.getLocalHost();
    entity.setIpAddress(addr.getHostAddress());
    }catch (UnknownHostException ue){

    }
    Set<Long> tenantIdList= adminUser.getTenantIdList();
    List<Long> result = new ArrayList<>(tenantIdList);
    Long tenantId = result.get(0);
    entity.setTenantId(tenantId);
    entity.setCreateDate(new Date());
    entity.setCreateUserId(adminUser.getAdminUser().getId());
    entity.setCreateUserName(adminUser.getAdminUser().getUsername());
    SysLoginInfoMapper.insertSelective(entity);
    return entity;
  }



  //获取加工企业登记审核列表
  public List<SysLoginInfo> getlist(SysLoginInfoDto query) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    // 处理tenant id list
    Set<Long> tenantIdList = new HashSet<>();
    Long tenantId = query.getTenantId();
    if (tenantId == null) {// 取出用户所属租户下所有的数据
      tenantIdList = adminUser.getTenantIdList();
    } else {
      if (!adminUser.getTenantIdList().contains(tenantId)) { // 判断前端传递的tenantId是否属于该用户
        throw new BusinessException(510, "前端传递的tenantId不属于该用户");
      }
      tenantIdList.add(tenantId);
    }

    query.setTenantIdList(tenantIdList);
    PageHelper.startPage(query.getPageNumber(), query.getPageSize());
    PageHelper.orderBy("t1.create_date desc");//排序
    List<SysLoginInfo> dbResult = SysLoginInfoMapper.selectList(query);
    return dbResult;
  }





}
